package top.rainbowecho.common.standard.database;

import top.rainbowecho.common.standard.database.function.SqlResultProcessor;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 杨健
 * @since 2019/8/22
 */
public class DatabaseHelper {
    private Connection conn = null;
    private PreparedStatement pStatement = null;
    private ResultSet resultSet = null;
    private PropertyConfiguration propertyConfiguration = new PropertyConfiguration();

    public DatabaseHelper() {
        propertyConfiguration.loadConnProperties();
    }


    private void openConnection(){
        try {
            Class.forName(propertyConfiguration.getDbDriver());
            this.conn = DriverManager.getConnection(propertyConfiguration.getDbURL(), propertyConfiguration.getUserName(), propertyConfiguration.getPassword());
        } catch(ClassNotFoundException classnotfoundexception) {
            classnotfoundexception.printStackTrace();
            System.err.println("db: " + classnotfoundexception.getMessage());
        } catch(SQLException sqlexception) {
            System.err.println("db.getconn(): " + sqlexception.getMessage());
        }
    }


    private void executeQuery(String sql) throws Exception {
        if (null == conn)
            throw new Exception("Database not connected!");
        pStatement = conn.prepareStatement(sql);
        resultSet = pStatement.executeQuery();
    }

    public List<String> selectSingleColumn(String sql, SqlResultProcessor processor) {
        try {
            openConnection();
            executeQuery(sql);
            ArrayList<String> results = new ArrayList<>(16);
            while (resultSet.next()) {
                results.add(processor.process(resultSet));
            }
            close();
            return results;
        } catch (Exception e) {
            return new ArrayList<>(0);
        }
    }

    // 释放资源
    private void close() {
        if (null != resultSet) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        resultSet = null;

        if (null != pStatement) {
            try {
                pStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(null != conn){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        conn = null;
    }

}
